import { JobOrderService } from 'src/app/@core/services/jobOrder/job-order.service';
import { Component } from '@angular/core';
import * as echarts from 'echarts';

@Component({
  selector: 'app-workbench-product',
  templateUrl: './workbench-product.component.html',
  styleUrls: ['./workbench-product.component.scss']
})
export class WorkbenchProductComponent {
  tabActiveId: string | number = 'tab1';
  activeTabData: any={
    "joborderAmount": 0,
    "joborderWeekUpRate": 0,
    "joborderProcessAmount": 0,
    "joborderProcessDateUpRate": 0,
    "completedJoborderProcessAmount": 0,
    "completedJoborderProcessDateUpRate": 0,
    "weeklyPassRate": 0,
    "weeklyPassRateWeekUpRate": 0
  }
  todolistData: any={}
  tabItems = [
    {
      id: 'tab1',
      title: '待生产',
    },
    {
      id: 'tab2',
      title: '未完结',
    }
  ]
  constructor(private JobOrderService:JobOrderService) {
  }
  ngOnInit(): void {
    this.JobOrderService.GetReportingPassRate().subscribe((data: any) => {
      this.deliveryData(data);
    }) // 获取报工合格率
    this.JobOrderService.GetAnnualJobOrderProcessCount().subscribe((data: any) => {
      const quantities = data.map((item: any) => item.jobOrderProcessMouthCount);
      this.saleData(quantities);
    }) // 获取年度工单工序数量
    this.JobOrderService.GetProductionJobOrderCountAndJobOrderProcessCountAlongWithGrowthRate().subscribe((data: any) => {
      this.activeTabData = data;
    }) // 获取工单数量和增长率
    this.JobOrderService.GetProductionTaskToDoList().subscribe((data: any) => {
      this.todolistData = data;
    }) // 获取待
    this.JobOrderService.GetTotalProduction().subscribe((data: any) => {
      this.renderDailyProductionChart(data);
    })
  }
  saleData(quantities: number[]): void {
    const option = {
      tooltip: {
        show: true,
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
        },
      },
      grid: {
        left: '5%',
        right: '5%',
        bottom: '5%',
        top: '12%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
      },
      yAxis: {
        type: 'value',
        name: '任务数',
        axisLine: {
          show: true,
        },
        axisLabel: {
          formatter: '{value} '
        }
      },
      series: [
        {
          data: quantities,
          name: "任务数",
          barWidth: '50%',
          type: 'bar',
          label: {
            show: true,
            position: 'top',
            formatter: function (params: any) {
              return `${params.value} `;
            }
          },
        }
      ]
    };
    const myChart = echarts.init(document.getElementById('xiaoshoue') as HTMLElement);
    myChart.setOption(option);
    myChart.resize(); // 初始化后立即调用 resize 方法
    window.addEventListener('resize', function () {
      myChart.resize();
    });
  }
  deliveryData(data: any): void {
    const option = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b} : {c} ({d}%)'
      },
      legend: {
        left: 'left',
        data: ['合格数', '不良数', '报废数']
      },
      series: [
        {
          name: '生产合格比率',
          type: 'pie',
          radius: '55%',
          center: ['50%', '60%'],
          data: [
            { value: data.totalQualifiedCount, name: '合格数' },
            { value: data.totalUnqualifiedCount, name: '不良数' },
            { value: data.totalScrapCount, name: '报废数' }
          ],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          },
          itemStyle: {
            color: function(params) {
              const colorList = ['#66bb6a', '#ffa726', '#ef5350'];
              return colorList[params.dataIndex];
            }
          }
        }
      ]
    };
    const myChart = echarts.init(document.getElementById('jiaofu') as HTMLElement);
    myChart.setOption(option);
    myChart.resize(); // 初始化后立即调用 resize 方法
    window.addEventListener('resize', function () {
      myChart.resize();
    });
  }
  getLastThreeDays(): string[] {
    const dates = [];
    for (let i = 2; i >= 0; i--) {
      const date = new Date();
      date.setDate(date.getDate() - i);
      const formattedDate = `${date.getMonth() + 1}月${date.getDate()}日`;
      dates.push(formattedDate);
    }
    return dates;
  }
  renderDailyProductionChart(data: any): void {
    const categories = ['生产数量', '在制数量', '完成数量'];
    const productionData = data.totalProductionQuantity; // 生产数量总和
    const inProgressData = data.totalStartQuantity + data.totalPausedQuantity;  // 在制数量总和
    const completedData = data.totalCompletedQuantity; // 完成数量总和

    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: categories
      },
      yAxis: {
        type: 'value',
        name: '数量',
        position: 'left'
      },
      series: [
        {
          name: '数量',
          type: 'bar',
          data: [productionData, inProgressData, completedData], // 每项对应一个柱状图
          itemStyle: {
            color: function(params) {
              const colorList = ['#42a5f5', '#ffa726', '#66bb6a']; // 蓝色系, 橙色系, 绿色系
              return colorList[params.dataIndex];
            }
          }
        }
      ]
    };

    const myChart = echarts.init(document.getElementById('dailyProductionChart') as HTMLElement);
    myChart.setOption(option);
    myChart.resize(); // 初始化后立即调用 resize 方法

    window.addEventListener('resize', function () {
      myChart.resize();
    });
  }
  getLastThreeMonths(): string[] {
    const months = [];
    const date = new Date();
    for (let i = 2; i >= 0; i--) {
      const d = new Date(date.getFullYear(), date.getMonth() - i, 1);
      const month = `${d.getFullYear()}年${d.getMonth() + 1}月`;
      months.push(month);
    }
    return months;
  }
  getReturnData(): number[] {
    // 模拟数据，可以替换为实际数据
    return [120, 200, 150];
  }
  getGrowthRateData(): number[] {
    const returnData = this.getReturnData();
    const growthRateData = [];

    for (let i = 1; i < returnData.length; i++) {
      const growthRate = ((returnData[i] - returnData[i - 1]) / returnData[i - 1]) * 100;
      growthRateData.push(parseFloat(growthRate.toFixed(2)));
    }

    // 为了保持数组长度一致，可以在开头插入一个默认值（如0或null）
    growthRateData.unshift(0);

    return growthRateData;
  }
}
